#include <stdio.h>
#include <cpar.h>

static CPARContext *pGlobalContext;

typedef struct CPARGlobalStackData CPARGlobalStackData;

struct CPARGlobalStackData
{
  CPAREvent *E;
};

static CPARGlobalStackData *pGlobalStack;

void CPARTask_tarefa1(CPARContext *pContext);
void CPARTask_tarefa2(CPARContext *pContext);
void CPARTask_tarefa3(CPARContext *pContext);

void CPARTask_tarefa1(CPARContext *pContext)
{ 
  CPAREventWait(pGlobalStack->E);
}

void CPARTask_tarefa2(CPARContext *pContext)
{ 
  CPAREventWait(pGlobalStack->E);
}

void CPARTask_tarefa3(CPARContext *pContext)
{ 
  CPAREventSet(pGlobalStack->E);
}

int main(int argc, char **argv)
{
  CPARInit();

  if( CPARContextCreate( NULL, &pGlobalContext, sizeof(CPARGlobalStackData) ))
  {
    CPAR_ERROR("Falha ao alocar contexto global");
    return CPAR_E_NO_MEMORY;
  }
  pGlobalStack = (CPARGlobalStackData*) CPARContextStackGet(pGlobalContext);

  if( CPARContextWorkPoolCreate( pGlobalContext, 3 ))
  {
    CPAR_ERROR("Falha ao alocar work pool");
    return -1;
  }

  CPAREventCreate(CPARContextAllocatorGet(pGlobalContext),&pGlobalStack->E);

  CPARContextTaskDispatch(pGlobalContext, 1, CPARTask_tarefa1, 0);
  CPARContextTaskDispatch(pGlobalContext, 1, CPARTask_tarefa2, 0);
  CPARContextTaskDispatch(pGlobalContext, 1, CPARTask_tarefa3, 0);

  CPARContextTaskWaitAll(pGlobalContext);

  CPAREventDestroy(pGlobalStack->E);

  return 0;
} 
